package com.android.love.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.android.app.sdk.AliPay;
import com.alipay.android.msp.Keys;
import com.alipay.android.msp.Result;
import com.alipay.android.msp.Rsa;
import com.android.love.R;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.ImageUtils;
import com.android.love.util.LogUtil;
import com.android.love.vo.Address;
import com.android.love.vo.Goods;
import com.android.love.vo.MyRequest;
import com.android.love.vo.Order;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.unionpay.UPPayAssistEx;

public class MyOrderDetail_1 extends BasePageActivity {
	private ViewFinder finder;
	// 订单状态
	private TextView tv_order_status;
	private TextView tv_order_id;
	private TextView tv_order_price;
	private TextView tv_order_kuaidi_id;
	private TextView tv_order_kuaidi_compare;
	private ImageView iv_zaixianzhifu;
	private LinearLayout ll_cart_img;
	private TextView tv_cart;
	private TextView tv_format;
	private TextView tv_address_text;
	private TextView tv_zhifu;
	private RelativeLayout rl_zhifu;
	private RelativeLayout rl_kuaidi;
	private TextView tv_kuaidi;
	private EditText et_liuyan;

	private int showNum;
	private Goods goods;

	// private int pay_id;
	private int orgin_express_id;

	private String[] pay_type = new String[] { "支付宝（推荐）", "银联支付" };
	private String[] express_type = new String[] { "普通快递（免运费）", "其他快递方式" };
	private List<Address> address_list = Collections.emptyList();
	private AlertDialog singleDialog;
	private Order order;
	private boolean cancel;
	private TextView tv_order_tip;
	private boolean showTip;

	private static final int RQF_PAY = 1;

	private static final int RQF_LOGIN = 2;

	// private int mGoodsIdx = 0;
	// private Handler mUHandler = null;
	// private ProgressDialog mLoadingDialog = null;

	private static final int PLUGIN_VALID = 0;
	private static final int PLUGIN_NOT_INSTALLED = -1;
	private static final int PLUGIN_NEED_UPGRADE = 2;

	/*****************************************************************
	 * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
	 *****************************************************************/
	private String mMode = "01";
	// private static final String TN_URL_01 =
	// "http://222.66.233.198:8080/sim/gettn";

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
			case RQF_LOGIN: {
				// Toast.makeText(MyOrderDetail_1.this, result.getResult(),
				// Toast.LENGTH_SHORT).show();
				result.parseResult();
				String statusCode = result.getResultStatus();
				LogUtil.i(TAG, "statusCode--" + statusCode);

				// sResultStatus.put("9000", "操作成功");
				// sResultStatus.put("4000", "系统异常");
				// sResultStatus.put("4001", "数据格式不正确");
				// sResultStatus.put("4003", "该用户绑定的支付宝账户被冻结或不允许支付");
				// sResultStatus.put("4004", "该用户已解除绑定");
				// sResultStatus.put("4005", "绑定失败或没有绑定");
				// sResultStatus.put("4006", "订单支付失败");
				// sResultStatus.put("4010", "重新绑定账户");
				// sResultStatus.put("6000", "支付服务正在进行升级操作");
				// sResultStatus.put("6001", "用户中途取消支付操作");
				// sResultStatus.put("7001", "网页支付失败");
				if ("9000".equals(statusCode)) {
					LogUtil.i(TAG, "statusCode--支付成功");
					// 支付成功
					MyRequest modifyReq = new MyRequest();
					modifyReq.authority = UriHelper.REALM_NAME;
					modifyReq.path = UriHelper.URL_ORDER_MODIFY;
					modifyReq.paramers = generateParams(0, 0, 2);
					getDataFromTask(context, ORDER_MODIFY, modifyReq,
							order.getStatus(), true, false);
					// ActivityUtil.show(MyOrderDetail_1.this, "支付成功");
					// Intent intent = new Intent(context,
					// MyOrderActivity.class);
					// startActivity(intent);
					// finish();
				} else if ("8000".equals(statusCode)) {
					// 支付处理中
					ActivityUtil.show(MyOrderDetail_1.this, "支付处理中");
					Intent intent = new Intent(context, MyOrderActivity.class);
					startActivity(intent);
					finish();
				} else {
					// 支付失败
					Toast.makeText(MyOrderDetail_1.this, result.getResult(),
							Toast.LENGTH_SHORT).show();
				}
				// if (statusCode == "4000") {
				// // 支付成功
				// }
				// if (statusCode == "4006") {
				// // 支付成功
				// }
				// if (statusCode == "6001") {
				// // 支付成功
				// }

			}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View view = inflater.inflate(R.layout.activity_order_detail_1, null);
		finder = new ViewFinder(view);
		setContentView(view);
		// 隐藏软键盘
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		process();
		setListener();
	}

	@Override
	protected Boolean loadBottomTab() {
		return false;
	}

	@Override
	protected void setListener() {
		super.setListener();
		finder.find(R.id.iv_shuaxin).setOnClickListener(this);
		finder.find(R.id.iv_top_meinv).setOnClickListener(this);
		finder.find(R.id.rl_cart_img).setOnClickListener(this);
		rl_zhifu.setClickable(false);
		rl_kuaidi.setClickable(false);
		tv_address_text.setClickable(false);
		iv_zaixianzhifu.setOnClickListener(this);
		// rl_kuaidi.setOnClickListener(this);
		// tv_address_text.setOnClickListener(this);
	}

	@Override
	protected void process() {
		super.process();
		Intent intent = getCurrentIntent();
		if (intent == null)
			finish(true);
		showTip = intent.getBooleanExtra("show", false);
		order = (Order) intent.getSerializableExtra("order");
		orgin_express_id = order.getExpress();
		if (showTip) {
			show(finder.find(R.id.tv_order_tip));
			finder.setDrawable(R.id.iv_shuaxin, R.drawable.btn_wcdd);
			finder.setText(R.id.top_title, "提交成功");
			hide(finder.find(R.id.iv_top_meinv));
		} else {
			hide(finder.find(R.id.tv_order_tip));
			finder.setDrawable(R.id.iv_shuaxin, R.drawable.btn_quxiaodingdan);
			finder.setText(R.id.top_title, "订单详情");
		}
		// tv_order_tip = ;

		tv_order_status = finder.find(R.id.tv_order_status);
		tv_order_id = finder.find(R.id.tv_order_id);
		tv_order_price = finder.find(R.id.tv_order_price);
		tv_order_kuaidi_id = finder.find(R.id.tv_order_kuaidi_id);
		tv_order_kuaidi_compare = finder.find(R.id.tv_order_kuaidi_compare);
		iv_zaixianzhifu = finder.find(R.id.iv_zaixianzhifu);
		ll_cart_img = finder.find(R.id.ll_cart_img);
		tv_cart = finder.find(R.id.tv_cart);
		tv_format = finder.find(R.id.tv_format);
		tv_address_text = finder.find(R.id.tv_address_text);
		tv_zhifu = finder.find(R.id.tv_zhifu);
		rl_zhifu = finder.find(R.id.rl_zhifu);
		rl_kuaidi = finder.find(R.id.rl_kuaidi);
		tv_kuaidi = finder.find(R.id.tv_kuaidi);
		et_liuyan = finder.find(R.id.et_liuyan);
		et_liuyan.setEnabled(false);
		changeStyle(order);

	}

	/**
	 * 改变样式
	 * 
	 * @param order
	 */
	private void changeStyle(Order order) {
		String html_status = null;
		switch (order.getStatus()) {
		case 1:
			// 订单未未支付
			hide(tv_order_kuaidi_id).hide(tv_order_kuaidi_compare);
			html_status = "<font color=\"#636363\">" + "订单状态： " + "</font>"
					+ "<font color=\"#ffcd00\">" + "等待付款" + "</font>";
			iv_zaixianzhifu.setImageResource(R.drawable.btn_zaixianzhifu);
			break;
		case 2:
			// 订单支付待发货
			hide(iv_zaixianzhifu).hide(tv_order_kuaidi_id).hide(
					tv_order_kuaidi_compare);
			html_status = "<font color=\"#636363\">" + "订单状态： " + "</font>"
					+ "<font color=\"#ffcd00\">" + "等待发货" + "</font>";
			hide(iv_zaixianzhifu);
			hide(finder.find(R.id.iv_shuaxin));
			break;
		case 3:
			// 订单已发货
			html_status = "<font color=\"#636363\">" + "订单状态： " + "</font>"
					+ "<font color=\"#ffcd00\">" + "已发货" + "</font>";
			iv_zaixianzhifu.setImageResource(R.drawable.btn_confirm_shouhuo);
			hide(finder.find(R.id.iv_shuaxin));
			break;
		case 4:
			// 订单已完成
			html_status = "<font color=\"#636363\">" + "订单状态： " + "</font>"
					+ "<font color=\"#ffcd00\">" + "已完成" + "</font>";
			hide(iv_zaixianzhifu);
			hide(finder.find(R.id.iv_shuaxin));
			break;
		case 5:
			// 订单已取消
			hide(tv_order_kuaidi_id).hide(tv_order_kuaidi_compare).hide(
					iv_zaixianzhifu);
			html_status = "<font color=\"#636363\">" + "订单状态： " + "</font>"
					+ "<font color=\"#ffcd00\">" + "订单已取消" + "</font>";
			hide(iv_zaixianzhifu);
			hide(finder.find(R.id.iv_shuaxin));
			break;

		default:
			break;
		}
		tv_order_status.setText(Html.fromHtml(html_status));
		tv_order_id.setText("订单号: " + order.getOrder_id());
		String html_price = "<font color=\"#636363\">" + "订单金额： " + "</font>"
				+ "<font color=\"#e2017b\">" + "￥ " + order.getSum()
				+ "</font>";
		tv_order_price.setText(Html.fromHtml(html_price));
		tv_order_kuaidi_id.setText("快递单号：" + order.getExpress_id());
		tv_order_kuaidi_compare.setText("快递公司：" + order.getExpress_agency());
		if (order.getGoods() != null) {

			if (order.getGoods().size() == 1) {
				tv_cart.setText(order.getGoods().get(0).getGoods_name());
				tv_format.setText(order.getGoods().get(0).getAttribute());
			} else {
				tv_cart.setVisibility(View.GONE);
				tv_format.setVisibility(View.GONE);
			}
			if (order.getGoods().size() <= 3) {
				showNum = order.getGoods().size();
			} else {
				showNum = 3;
			}
			for (int i = 0; i < showNum; i++) {
				ImageView imgImageView = new ImageView(context);
				ll_cart_img.addView(imgImageView);
				// LayoutParams params=(LayoutParams)
				// imgImageView.getLayoutParams();
				// imgImageView.setBackgroundResource(R.drawable.beijing2);
				// params.setMargins(10, 10, 10, 10);
				// imgImageView.setLayoutParams(params);
				loader.displayImageForSize(order.getGoods().get(i)
						.getGoods_image(), imgImageView,
						ImageUtils.getOptions(R.drawable.zw2),
						new SimpleImageLoadingListener(), 10, 10, 10, 10, 0, 0,
						6f, false);
			}
		}
		tv_address_text.setText(order.getConsignee() + "  " + order.getPhone()
				+ "\n" + order.getAddress() + "  " + order.getPostal());
		switch (order.getChannel()) {
		case 1:
			tv_zhifu.setText("支付方式:支付宝(推荐)");
			break;
		case 2:
			tv_zhifu.setText("支付方式:银联支付");
			break;

		default:
			break;
		}
		switch (order.getExpress()) {
		case 1:
			tv_kuaidi.setText("快递方式:普通快递(免运费)");
			break;
		case 2:
			tv_kuaidi.setText("快递方式:其他快递");
			break;

		default:
			break;
		}
		if (order.getStatus() != 1)
			et_liuyan.setFocusable(false);
		if ("".equals(order.getMsg().trim()))
			et_liuyan.setHint("快递时记得将商品包装一起邮寄");
		else
			et_liuyan.setText(order.getMsg());
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_shuaxin:
			if (showTip) {
				// 完成订单
				if (order.getChannel() == 1) {
					// 支付宝
					try {
						Log.i("ExternalPartner", "onItemClick");
						String info = getNewOrderInfo();
						String sign = Rsa.sign(info, Keys.PRIVATE);
						sign = URLEncoder.encode(sign);
						info += "&sign=\"" + sign + "\"&" + getSignType();
						Log.i("ExternalPartner", "start pay");
						// start the pay.
						Log.i(TAG, "info = " + info);

						final String orderInfo = info;
						new Thread() {
							public void run() {
								AliPay alipay = new AliPay(
										MyOrderDetail_1.this, mHandler);

								// 设置为沙箱模式，不设置默认为线上环境
								// alipay.setSandBox(true);

								String result = alipay.pay(orderInfo);

								Log.i(TAG, "result = " + result);
								Message msg = new Message();
								msg.what = RQF_PAY;
								msg.obj = result;
								mHandler.sendMessage(msg);
							}
						}.start();

					} catch (Exception ex) {
						ex.printStackTrace();
						Toast.makeText(MyOrderDetail_1.this,
								R.string.remote_call_failed, Toast.LENGTH_SHORT)
								.show();
					}
				} else {
					// // 银联
					// Log.e(TAG, " " + v.getTag());
					// mGoodsIdx = (Integer) v.getTag();
					//
					// mLoadingDialog = ProgressDialog.show(context, // context
					// "", // title
					// "正在努力的获取tn中,请稍候...", // message
					// true); // 进度是否是不确定的，这只和创建进度条有关
					//
					// /*************************************************
					// *
					// * 步骤1：从网络开始,获取交易流水号即TN
					// *
					// ************************************************/
					// new Thread(MyOrderDetail_1.this).run();

					/*************************************************
					 * 
					 * 步骤2：通过银联工具类启动支付插件
					 * 
					 ************************************************/
					// mMode参数解释：
					// 0 - 启动银联正式环境
					// 1 - 连接银联测试环境
					int ret = UPPayAssistEx.startPay(this, null, null,
							order.getTrade_no() + "", mMode);
					if (ret == PLUGIN_NEED_UPGRADE
							|| ret == PLUGIN_NOT_INSTALLED) {
						// 需要重新安装控件
						Log.e(TAG, " plugin not found or need upgrade!!!");

						AlertDialog.Builder builder = new AlertDialog.Builder(
								this);
						builder.setTitle("提示");
						builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

						builder.setNegativeButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										// 安装Asset中提供的UPPayPlugin.apk
										// 此处可根据实际情况,添加相应的处理逻辑
										UPPayAssistEx
												.installUPPayPlugin(MyOrderDetail_1.this);
									}
								});

						builder.setPositiveButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
						builder.create().show();

					}
					Log.e(TAG, "" + ret);
				}
			} else {
				// 取消订单
				newYesNoDialog(R.string.cancel_title, R.string.delete_message,
						new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								if (which == DialogInterface.BUTTON_POSITIVE) {
									MyRequest modifyReq = new MyRequest();
									modifyReq.authority = UriHelper.REALM_NAME;
									modifyReq.path = UriHelper.URL_ORDER_MODIFY;
									modifyReq.paramers = generateParams(0, 0, 5);
									getDataFromTask(context, ORDER_MODIFY,
											modifyReq, order.getStatus(), true,
											false);
								}

							}
						}).show();
			}

			break;
		case R.id.rl_cart_img:
			if (order.getGoods().size() > 1) {
				Intent intent = new Intent(context, MyOrderDetail_2.class);
				intent.putExtra("order_detail", order);
				startActivity(intent);
				ActivityUtil.runActivityAnim(MyOrderDetail_1.this, false);
			} else {
				// 单个商品
				MyRequest singleReq = new MyRequest();
				singleReq.authority = UriHelper.REALM_NAME;
				singleReq.path = UriHelper.URL_GOODS;
				singleReq.paramers = generateParams(-1, order.getGoods().get(0)
						.getGoods_id(), -1);
				getDataFromTask(context, GOODS, singleReq, goods, true, false);
			}
			break;
		// case R.id.rl_zhifu:
		// if (order.getStatus() != 1)
		// return;
		// singleDialog = new AlertDialog.Builder(context)
		// .setTitle("支付方式")
		// .setSingleChoiceItems(pay_type, order.getChannel() - 1,
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// order.setChannel(which + 1);
		// tv_zhifu.setText("支付方式：" + pay_type[which]);
		// singleDialog.dismiss();
		// }
		// }).create();
		// singleDialog.show();
		// break;
		// case R.id.rl_kuaidi:
		// if (order.getStatus() != 1)
		// return;
		// singleDialog = new AlertDialog.Builder(context)
		// .setTitle("快递方式")
		// .setSingleChoiceItems(express_type, order.getExpress() - 1,
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// switch (which) {
		// case 0:
		// // yunfei = 0;
		// order.setExpress(1);
		// if (orgin_express_id == 2) {
		// order.setSum(order.getSum() - 10);
		// String html_price = "<font color=\"#636363\">"
		// + "订单金额： "
		// + "</font>"
		// + "<font color=\"#e2017b\">"
		// + "￥ "
		// + order.getSum()
		// + "</font>";
		// tv_order_price.setText(Html
		// .fromHtml(html_price));
		// }
		// break;
		// case 1:
		// // yunfei = 10;
		// order.setExpress(2);
		// if (orgin_express_id == 1) {
		// order.setSum(order.getSum() + 10);
		// String html_price = "<font color=\"#636363\">"
		// + "订单金额： "
		// + "</font>"
		// + "<font color=\"#e2017b\">"
		// + "￥ "
		// + order.getSum()
		// + "</font>";
		// tv_order_price.setText(Html
		// .fromHtml(html_price));
		// }
		// break;
		//
		// default:
		// break;
		// }
		// // updateTotalPrice();
		// // express = which;
		// tv_kuaidi.setText("快递方式："
		// + express_type[which]);
		// singleDialog.dismiss();
		// }
		// }).create();
		// singleDialog.show();
		// break;
		// case R.id.tv_address_text:
		// if (order.getStatus() != 1)
		// return;
		// MyRequest addressReq = new MyRequest();
		// addressReq.authority = UriHelper.REALM_NAME;
		// addressReq.path = UriHelper.URL_ADDRESS_LIST;
		// addressReq.paramers = generateParams(1, 0, -1);
		// getDataFromTask(context, ADDRESS_LIST, addressReq, address_list,
		// true, false);
		// break;
		case R.id.iv_top_meinv:
			Intent intent = new Intent();
			intent.putExtra("cancel", cancel);
			setResult(1, intent);
			finish(true);
			break;
		case R.id.iv_zaixianzhifu:

			if (order.getStatus() == 1) {
				// 在线支付
				if (order.getChannel() == 1) {
					// 支付宝
					try {
						Log.i("ExternalPartner", "onItemClick");
						String info = getNewOrderInfo();
						String sign = Rsa.sign(info, Keys.PRIVATE);
						sign = URLEncoder.encode(sign);
						info += "&sign=\"" + sign + "\"&" + getSignType();
						Log.i("ExternalPartner", "start pay");
						// start the pay.
						Log.i(TAG, "info = " + info);

						final String orderInfo = info;
						new Thread() {
							public void run() {
								AliPay alipay = new AliPay(
										MyOrderDetail_1.this, mHandler);

								// 设置为沙箱模式，不设置默认为线上环境
								// alipay.setSandBox(true);

								String result = alipay.pay(orderInfo);

								Log.i(TAG, "result = " + result);
								Message msg = new Message();
								msg.what = RQF_PAY;
								msg.obj = result;
								mHandler.sendMessage(msg);
							}
						}.start();

					} catch (Exception ex) {
						ex.printStackTrace();
						Toast.makeText(MyOrderDetail_1.this,
								R.string.remote_call_failed, Toast.LENGTH_SHORT)
								.show();
					}
				} else {
					// 银联
					/*************************************************
					 * 
					 * 步骤2：通过银联工具类启动支付插件
					 * 
					 ************************************************/
					// mMode参数解释：
					// 0 - 启动银联正式环境
					// 1 - 连接银联测试环境
					int ret = UPPayAssistEx.startPay(this, null, null,
							order.getTrade_no() + "", mMode);
					if (ret == PLUGIN_NEED_UPGRADE
							|| ret == PLUGIN_NOT_INSTALLED) {
						// 需要重新安装控件
						Log.e(TAG, " plugin not found or need upgrade!!!");

						AlertDialog.Builder builder = new AlertDialog.Builder(
								this);
						builder.setTitle("提示");
						builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

						builder.setNegativeButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
										// 安装Asset中提供的UPPayPlugin.apk
										// 此处可根据实际情况,添加相应的处理逻辑
										UPPayAssistEx
												.installUPPayPlugin(MyOrderDetail_1.this);
									}
								});

						builder.setPositiveButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								});
						builder.create().show();

					}
					Log.e(TAG, "" + ret);
				}

			}
			if (order.getStatus() == 3) {
				// 确认收货
				MyRequest modifyReq = new MyRequest();
				modifyReq.authority = UriHelper.REALM_NAME;
				modifyReq.path = UriHelper.URL_ORDER_MODIFY;
				modifyReq.paramers = generateParams(0, 0, 4);
				getDataFromTask(context, ORDER_MODIFY, modifyReq,
						order.getStatus(), true, false);
			}
			// Intent intent = new Intent();
			// intent.putExtra("cancel", cancel);
			// setResult(1, intent);
			// finish(true);
			break;

		default:
			break;
		}
	}

	@Override
	public void handle(int tag, Object object) {
		super.handle(tag, object);
		switch (tag) {
		case ORDER_MODIFY:
			if (object != null) {
				int status = (Integer) object;
				if (status > 0) {
					order.setStatus(status);
					if (status == 5) {
						// 取消订单
						cancel = true;
						ActivityUtil.show(MyOrderDetail_1.this, "取消订单成功");
						Intent intent = new Intent();
						intent.putExtra("cancel", cancel);
						setResult(RESULT_OK, intent);
						finish(true);
					} else if (status == 4) {
						// 完成订单
						if (showTip) {
							ActivityUtil.show(MyOrderDetail_1.this, "支付成功");
							int order_num = sp.getValue(ORDER_NUM, 0);
							sp.setValue(ORDER_NUM, --order_num);
							updateBottomOrder();
							Intent intent = new Intent(context,
									MyOrderActivity.class);
							startActivity(intent);
							finish();
						} else {
							ActivityUtil.show(MyOrderDetail_1.this, "订单已完成");
							Intent intent = new Intent();
							intent.putExtra("wancheng", true);
							setResult(RESULT_OK, intent);
							finish(true);
						}

					} else if (status == 2) {
						if (showTip) {
							ActivityUtil.show(MyOrderDetail_1.this,
									"订单已支付，请等待发货");
							int order_num = sp.getValue(ORDER_NUM, 0);
							sp.setValue(ORDER_NUM, --order_num);
							updateBottomOrder();
							Intent intent = new Intent(context,
									MyOrderActivity.class);
							startActivity(intent);
							finish();
						} else {
							// 订单已支付待发货
							ActivityUtil.show(MyOrderDetail_1.this,
									"订单已支付，请等待发货");
							Intent intent = new Intent();
							intent.putExtra("zhifu", true);
							setResult(RESULT_OK, intent);
							finish(true);
						}
					}
					// changeStyle(order);
				}
			}
			break;
		case GOODS:
			if (object != null) {
				goods = (Goods) object;
				Intent intent = new Intent(context, DetailActivity.class);
				intent.putExtra("type", 1);
				intent.putExtra("singleGoods", goods);
				startActivity(intent);
				ActivityUtil.runActivityAnim(MyOrderDetail_1.this, false);
			}
			break;
		case ADDRESS_LIST:
			if (object != null) {
				address_list = (List<Address>) object;
				if (address_list.size() > 0) {
					// 选择地址
					// String[] address_type = null;
					StringBuilder sb = new StringBuilder();
					for (int i = 0; i < address_list.size(); i++) {
						if (i < address_list.size() - 1) {
							sb.append(address_list.get(i).getAddress()).append(
									",");
						} else {
							sb.append(address_list.get(i).getAddress());
						}
					}
					singleDialog = new AlertDialog.Builder(context)
							.setTitle("地址选择")
							.setSingleChoiceItems(sb.toString().split(","), 0,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											Address address = address_list
													.get(which);
											tv_address_text.setText(address
													.getConsignee()
													+ "  "
													+ address.getPhone()
													+ "\n"
													+ address.getAddress()
													+ "  "
													+ address.getPostal());
											order.setAddress(address
													.getAddress());
											singleDialog.dismiss();
										}
									}).create();
					singleDialog.show();
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams(int page, long goods_id,
			int status) {
		JSONObject json = new JSONObject();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		if (page == -1) {
			params.put("goods_id", goods_id + "");
		} else {
			if (status == -1) {
				params.put("page", page + "");
				params.put("count", "10");
			} else {
				params.put("order_id", order.getOrder_id() + "");
				params.put("status", status + "");
			}
			if (sp.getValue(USER_ID, 0) != 0)
				params.put("user_id", sp.getValue(USER_ID, 0) + "");
			if (!"".equals(sp.getValue(SIG, "")))
				params.put("sig", sp.getValue(SIG, ""));
		}
		return params;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			intent.putExtra("cancel", cancel);
			setResult(1, intent);
			finish(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 支付宝订单信息
	 * 
	 * @return
	 */
	private String getNewOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(order.getOrder_id());
		sb.append("\"&subject=\"");
		if (order.getGoods().size() == 1)
			sb.append(order.getGoods().get(0).getGoods_name());
		else
			sb.append(order.getGoods().get(0).getGoods_name() + "等"
					+ order.getGoods().size() + "件商品");
		sb.append("\"&body=\"");
		if (order.getGoods().size() == 1)
			sb.append(order.getGoods().get(0).getAttribute());
		else
			sb.append(order.getGoods().size() + "件商品");
		sb.append("\"&total_fee=\"");
		sb.append(order.getSum());
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder.encode(UriHelper.REALM_NAME+UriHelper.ONLINEPAY));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	// @Override
	// public void run() {
	// String tn = null;
	// InputStream is;
	// try {
	//
	// String url = TN_URL_01;
	//
	// URL myURL = new URL(url);
	// URLConnection ucon = myURL.openConnection();
	// ucon.setConnectTimeout(120000);
	// is = ucon.getInputStream();
	// int i = -1;
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// while ((i = is.read()) != -1) {
	// baos.write(i);
	// }
	//
	// tn = baos.toString();
	// is.close();
	// baos.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// Message msg = mUHandler.obtainMessage();
	// msg.obj = tn;
	// mHandler.sendMessage(msg);
	// }
	//
	// @Override
	// public boolean handleMessage(Message msg) {
	// Log.e(TAG, " " + "" + msg.obj);
	// if (mLoadingDialog.isShowing()) {
	// mLoadingDialog.dismiss();
	// }
	//
	// String tn = "";
	// if (msg.obj == null || ((String) msg.obj).length() == 0) {
	// AlertDialog.Builder builder = new AlertDialog.Builder(this);
	// builder.setTitle("错误提示");
	// builder.setMessage("网络连接失败,请重试!");
	// builder.setNegativeButton("确定",
	// new DialogInterface.OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// dialog.dismiss();
	// }
	// });
	// builder.create().show();
	// } else {
	// tn = (String) msg.obj;
	// /*************************************************
	// *
	// * 步骤2：通过银联工具类启动支付插件
	// *
	// ************************************************/
	// // mMode参数解释：
	// // 0 - 启动银联正式环境
	// // 1 - 连接银联测试环境
	// int ret = UPPayAssistEx.startPay(this, null, null, tn, mMode);
	// if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
	// // 需要重新安装控件
	// Log.e(TAG, " plugin not found or need upgrade!!!");
	//
	// AlertDialog.Builder builder = new AlertDialog.Builder(this);
	// builder.setTitle("提示");
	// builder.setMessage("完成购买需要安装银联支付控件，是否安装？");
	//
	// builder.setNegativeButton("确定",
	// new DialogInterface.OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// dialog.dismiss();
	// }
	// });
	//
	// builder.setPositiveButton("取消",
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// dialog.dismiss();
	// }
	// });
	// builder.create().show();
	//
	// }
	// Log.e(TAG, "" + ret);
	// }
	// return false;
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*************************************************
		 * 
		 * 步骤3：处理银联手机支付控件返回的支付结果
		 * 
		 ************************************************/
		if (data == null) {
			return;
		}

		String msg = "";
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		String str = data.getExtras().getString("pay_result");
		if (str.equalsIgnoreCase("success")) {
			msg = "支付成功！";
			ActivityUtil.show(MyOrderDetail_1.this, msg);
			MyRequest modifyReq = new MyRequest();
			modifyReq.authority = UriHelper.REALM_NAME;
			modifyReq.path = UriHelper.URL_ORDER_MODIFY;
			modifyReq.paramers = generateParams(0, 0, 2);
			getDataFromTask(context, ORDER_MODIFY, modifyReq,
					order.getStatus(), true, false);
		} else if (str.equalsIgnoreCase("fail")) {
			msg = "支付失败！";
			ActivityUtil.show(MyOrderDetail_1.this, msg);
		} else if (str.equalsIgnoreCase("cancel")) {
			msg = "用户取消了支付";
			ActivityUtil.show(MyOrderDetail_1.this, msg);
		}

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// builder.setTitle("支付结果通知");
		// builder.setMessage(msg);
		// builder.setInverseBackgroundForced(true);
		// // builder.setCustomTitle();
		// builder.setNegativeButton("确定", new DialogInterface.OnClickListener()
		// {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.dismiss();
		// }
		// });
		// builder.create().show();
	}
}
